package org.third.common.utils;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

/**
 * Created by Huailong Tang(Jason) on 2017/8/31.
 */
public class CustomResponseErrorHandler implements ResponseErrorHandler {

  private static final Logger logger = LoggerFactory.getLogger(CustomResponseErrorHandler.class);

  @Override
  public void handleError(ClientHttpResponse clienthttpresponse) throws IOException {

    if (clienthttpresponse.getStatusCode() == HttpStatus.FORBIDDEN) {
      logger.debug(HttpStatus.FORBIDDEN + " response. Throwing authentication exception");
      throw new RuntimeException();
    }
  }

  @Override
  public boolean hasError(ClientHttpResponse clienthttpresponse) throws IOException {

    if (clienthttpresponse.getStatusCode() != HttpStatus.OK) {

//      logger.debug("Request Status code: {} ",clienthttpresponse.getStatusCode());
//      logger.debug("Response Status info {}",clienthttpresponse.getStatusText());
//      logger.debug("Response body {}", IOUtils.toString(clienthttpresponse.getBody(), StandardCharsets.UTF_8));

      if (clienthttpresponse.getStatusCode() == HttpStatus.FORBIDDEN) {
        logger.debug("Call returned a error 403 forbidden resposne ");
        return true;
      }
    }
    return false;
  }
}
